<?php

namespace app\admin\controller;

use app\admin\model\AdminLog;
use app\common\controller\Backend;
use think\Config;
use think\Hook;
use think\Session;
use think\Validate;
use app\common\library\Sms as Smslib;
use fast\Random;
use think\Db;

/**
 * 后台首页
 * @internal
 */
class Index extends Backend
{

    protected $noNeedLogin = ['login', 'sendsms'];
    protected $noNeedRight = ['index', 'logout', 'notify'];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');
    }
    /**
     * 后台首页
     */
    public function sendsms()
    {
        $mobile = $this->request->post("username");
        $event = $this->request->post("event");

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        $last = Smslib::get($mobile, $event);
        if ($last && time() - $last['createtime'] < 60) {
            $this->error(__('发送频繁'));
        }
        $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
        if ($ipSendTotal >= 5) {
            $this->error(__('发送频繁'));
        }
        $admin =  db::table('fa_admin')->where('username', $mobile)->find();
        if (!$admin) {
            $this->error(__('用户不存在，请联系管理员'));
        }
        if (!Hook::get('sms_send')) {
            $this->error(__('请在后台插件管理安装短信验证插件'));
        }
        $ret = Smslib::send($mobile, null, $event);
        if ($ret) {
            $this->success(__('发送成功'));
        } else {
            $this->error(__('发送失败，请检查短信配置是否正确'));
        }
    }
    /**
     * 后台首页
     */
    public function index()
    {
        $cookieArr = ['adminskin' => "/^skin\-([a-z\-]+)\$/i", 'multiplenav' => "/^(0|1)\$/", 'multipletab' => "/^(0|1)\$/", 'show_submenu' => "/^(0|1)\$/"];
        foreach ($cookieArr as $key => $regex) {
            $cookieValue = $this->request->cookie($key);
            if (!is_null($cookieValue) && preg_match($regex, $cookieValue)) {
                config('fastadmin.' . $key, $cookieValue);
            }
        }
        //左侧菜单
        list($menulist, $navlist, $fixedmenu, $referermenu) = $this->auth->getSidebar([
            'dashboard' => 'hot',
            'addon'     => ['new', 'red', 'badge'],
            'auth/rule' => __('Menu'),
        ], $this->view->site['fixedpage']);
        $action = $this->request->request('action');
        if ($this->request->isPost()) {
            if ($action == 'refreshmenu') {
                $this->success('', null, ['menulist' => $menulist, 'navlist' => $navlist]);
            }
        }
        $this->assignconfig('cookie', ['prefix' => config('cookie.prefix')]);
        $this->view->assign('menulist', $menulist);
        $this->view->assign('navlist', $navlist);
        $this->view->assign('fixedmenu', $fixedmenu);
        $this->view->assign('referermenu', $referermenu);
        $this->view->assign('title', __('Home'));
        $gr =  db::table('fa_tongzhi')->where('type', '2')->where('admin_id', $this->auth->id)->limit(30)->select();
        $xt =  db::table('fa_tongzhi')->where('type', '1')->limit(30)->select();
        //  return json($xt);
        $tongzhi = array_merge($gr, $xt);
        $sort = array_column($tongzhi, 'id');
        array_multisort($sort, SORT_DESC, $tongzhi);
        $data = [];
        foreach ($tongzhi as $key => $value) {
            $p = db::table('fa_tongzhi_yidu')->where('tongzhi_id', $value['id'])->where('admin_id', $this->auth->id)->find();
            if (!$p) {
                $value['date'] = date('Y/m/d', $value['createtime']);
                $data[] = $value;
            }
        }
        //   return json($data);
        $this->view->assign('tongzhi', $data);
        $this->view->assign('tongzhinum', count($data));
        return $this->view->fetch();
    }
    public  function notify()
    {
        $id = $this->request->request('message_id');
        $gr =  db::table('fa_tongzhi')->where('id', $id)->find();
        if (!$gr) {
            $this->error('消息不存在，请联系管理员');
        }
        if ($gr['type'] == 2 && $gr['admin_id'] != $this->auth->id) {
            $this->error('消息不存在，请联系管理员');
        }
        db::table('fa_tongzhi_yidu')->insert(['tongzhi_id' => $id, 'admin_id' => $this->auth->id]);
        return $this->success('', '', $gr['content']);
    }
    /**
     * 管理员登录
     */
    public function login()
    {
        $url = $this->request->get('url', '', 'url_clean');
        $url = $url ?: 'index/index';
        if ($this->auth->isLogin()) {
            $this->success(__("You've logged in, do not login again"), $url);
        }
        //保持会话有效时长，单位:小时
        $keeyloginhours = 24 * 30;
        if ($this->request->isPost()) {
            $login_type = $this->request->post('login_type');
            $keeplogin = 1;
            if ($login_type == "mobile") { //短信
                $username = $this->request->post('username');
                if (!$username || !\think\Validate::regex($username, "^1\d{10}$")) {
                    $this->error(__('手机号不正确'));
                }
                $captcha = $this->request->post('code');
                $event = "adminlogin";
                $ret = Smslib::check($username, $captcha, $event);
                if (!$ret) {
                    $this->error('短信验证失败', $url, ['token' => $this->request->token()]);
                }
                $password = Random::alpha(10);
                $result = $this->auth->loginSms($username, $keeplogin ? $keeyloginhours * 3600 : 0);
            } else {
                $username = $this->request->post('username');
                $password = $this->request->post('password', '', null);
                $keeplogin = $this->request->post('keeplogin', 1);
                $token = $this->request->post('__token__');
                $rule = [
                    'username'  => 'require|length:3,30',
                    'password'  => 'require|length:3,30',
                    '__token__' => 'require|token',
                ];
                $data = [
                    'username'  => $username,
                    'password'  => $password,
                    '__token__' => $token,
                ];
                if (Config::get('fastadmin.login_captcha')) {
                    $rule['captcha'] = 'require|captcha';
                    $data['captcha'] = $this->request->post('captcha');
                }
                $validate = new Validate($rule, [], ['username' => __('Username'), 'password' => __('Password'), 'captcha' => __('Captcha')]);
                $result = $validate->check($data);
                if (!$result) {
                    $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
                }
                $result = $this->auth->login($username, $password, $keeyloginhours * 3600);
            }

            AdminLog::setTitle(__('Login'));

            if ($result === true) {
                Hook::listen("admin_login_after", $this->request);
                $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ? $msg : __('Username or password is incorrect');
                $this->error($msg, $url, ['token' => $this->request->token()]);
            }
        }

        // 根据客户端的cookie,判断是否可以自动登录
        if ($this->auth->autologin()) {
            Session::delete("referer");
            $this->redirect($url);
        }
        $background = Config::get('fastadmin.login_background');
        $background = $background ? (stripos($background, 'http') === 0 ? $background : config('site.cdnurl') . $background) : '';
        $this->view->assign('keeyloginhours', $keeyloginhours);
        $this->view->assign('background', $background);
        $this->view->assign('title', __('Login'));
        Hook::listen("admin_login_init", $this->request);
        return $this->view->fetch();
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        if ($this->request->isPost()) {
            $this->auth->logout();
            Hook::listen("admin_logout_after", $this->request);
            $this->success(__('Logout successful'), 'index/login');
        }
        $html = "<form id='logout_submit' name='logout_submit' action='' method='post'>" . token() . "<input type='submit' value='ok' style='display:none;'></form>";
        $html .= "<script>document.forms['logout_submit'].submit();</script>";

        return $html;
    }
}
